﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Mapping.Attributes;
using NHibernate.Transform;
using NHibernate.Criterion;
using System.Xml;
using System.IO;

namespace Service
{
    /// <summary>
    /// Сводное описание для WebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // Чтобы разрешить вызывать веб-службу из скрипта с помощью ASP.NET AJAX, раскомментируйте следующую строку. 
    // [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {      
        string GetAttribute(XmlNode node, string Name)
        {
            return node.Attributes[Name].Value;
        }
        [WebMethod]
        public bool writeCustomerToBase(string s)
        {
            int id_affiliateaddress = 10;
            int id_company = 11;
            try
            {
                

                ISession session = DataLayer.OpenSession();
                ITransaction tr = session.BeginTransaction();
               
                CCPerson person = new CCPerson();
                CreditPerson cperson = new CreditPerson();
                //person.ID_Customer = id_customer;

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(s);
                
                foreach (XmlNode xmln in doc.ChildNodes)
                {
                    //if (xmln.Name=="root")
                    //{
                        foreach (XmlNode xm in xmln.ChildNodes)
                        {
                            #region сохранение анкеты
                            if (xm.Name == "First")
                            {
                                person.Surname = GetAttribute(xm, "Surname");
                                person.Name = GetAttribute(xm, "Name");
                                person.Patroname = GetAttribute(xm, "Patroname");
                                person.ID_Gender = Convert.ToInt32(GetAttribute(xm, "ID_Gender"));
                                person.BirthdayRegion = GetAttribute(xm, "BirthdayRegion");
                                person.Birthday = Convert.ToDateTime(GetAttribute(xm, "BirthdayDate"));
                                person.BirthdayDistrict = GetAttribute(xm, "BirthdayRayon");
                                person.BirthdayCity = GetAttribute(xm, "BirthdayCity");
                                person.BirthdayPlace = GetAttribute(xm, "BirtdayPlace");
                                person.CreateTimeStamp = DateTime.Now;

                                List<CCMaritalStatus> lMaritalStatus = (List<CCMaritalStatus>)session.CreateCriteria(typeof(CCMaritalStatus)).List<CCMaritalStatus>();
                                person.MaritalStatus = lMaritalStatus.Find(delegate(CCMaritalStatus bk) { return bk.ID_MaritalStatus == Convert.ToInt32(GetAttribute(xm, "ID_MaritalStatus")); });

                                List<CCEducation> lEducation = (List<CCEducation>)session.CreateCriteria(typeof(CCEducation)).List<CCEducation>();
                                person.Education = lEducation.Find(delegate(CCEducation bk) { return bk.ID_Education == Convert.ToInt32(GetAttribute(xm, "ID_Education")); });

                                person.PassportNum = Convert.ToInt64(GetAttribute(xm, "PassportNum"));
                                person.PassportPlace = GetAttribute(xm, "PassportPlace");
                                person.PassportDate = Convert.ToDateTime(GetAttribute(xm, "PassportDate"));
                                person.ID_Company = id_company;
                                person.ID_AAddress = id_affiliateaddress;
                                person.ID_Parent = 0;
                                person.Level = 0;
                                person.CreateTimeStamp = DateTime.Today;
                                session.Save(person);
                            }
                            
                            foreach (XmlNode xml in xm.ChildNodes)
                            {
                                if (xml.Name == "Phone")
                                {
                                    CCPhone phone = new CCPhone();
                                    phone.ID_Customer = person.ID_Customer;
                                    phone.ID_PhoneType = Convert.ToInt32(GetAttribute(xml, "TypePhone"));
                                    phone.Mask = GetAttribute(xml, "Mask");
                                    phone.Number = Convert.ToInt64(GetAttribute(xml, "PhoneNumber"));
                                    //сохраняем данные по клиенту в m_customercard_phone
                                    session.Save(phone);

                                }
                                if (xml.Name == "SecondDoc")
                                {
                                    CreditSecondDoc secondDoc = new CreditSecondDoc();
                                    secondDoc.ID_Customer = person.ID_Customer;
                                    secondDoc.ID_SecondDocType = Convert.ToInt32(GetAttribute(xml, "ID_TypeSecondDoc"));
                                    secondDoc.Number = GetAttribute(xml, "Number");

                                    //сохраняем второй документ в m_credit_seconddocs
                                    session.Save(secondDoc);

                                }
                                if (xml.Name == "Address")
                                {
                                    CCAddress address = new CCAddress();
                                    address.AddressIndex = Convert.ToInt32(GetAttribute(xml, "AddressIndex"));
                                    address.ID_AddressType = Convert.ToInt32(GetAttribute(xml, "ID_AddressType"));
                                    address.Region = GetAttribute(xml, "Area");
                                    address.Area = GetAttribute(xml, "Rayon");
                                    address.City = GetAttribute(xml, "City");
                                    address.Street = GetAttribute(xml, "Street");
                                    address.HouseNumber = GetAttribute(xml, "HouseNumber");
                                    address.HouseType = Convert.ToInt32(GetAttribute(xml, "HouseType"));
                                    address.Korpus = GetAttribute(xml, "Korpus");
                                    address.KorpusType = Convert.ToInt32(GetAttribute(xml, "KorpusType"));
                                    address.Flat = GetAttribute(xml, "Flat");
                                    address.FlatType = Convert.ToInt32(GetAttribute(xml, "FlatType"));

                                    //сохраняем адрес в m_customer
                                    session.Save(address);

                                }
                                if (xml.Name == "Referess")
                                {
                                    CCPerson personreferess = new CCPerson();
                                    personreferess.Surname = GetAttribute(xml, "Surname");
                                    personreferess.Name = GetAttribute(xml, "Name");
                                    personreferess.Patroname = GetAttribute(xml, "Patroname");
                                    personreferess.IsClosePerson = "1".Equals(GetAttribute(xml, "ClosePeople"));
                                    personreferess.ID_ParentRelation = Convert.ToInt32(GetAttribute(xml, "ParentRelation"));
                                    person.ID_Company = id_company;
                                    person.ID_AAddress = id_affiliateaddress;
                                    personreferess.ID_Parent = person.ID_Customer;
                                    personreferess.Level = 1;
                                    personreferess.CreateTimeStamp = DateTime.Now;

                                    session.Save(personreferess);


                                    CCPhone phonereferess = new CCPhone();
                                    phonereferess.ID_PhoneType = Convert.ToInt32(GetAttribute(xml, "typePhone"));
                                    phonereferess.ID_Customer = personreferess.ID_Customer;
                                    phonereferess.Number = Convert.ToInt64(GetAttribute(xml, "phoneNumber"));
                                    phonereferess.Mask = GetAttribute(xml, "Mask");

                                    session.Save(phonereferess);

                                }

                                if (xml.Name == "RukWork")
                                {
                                    CCPerson personruk = new CCPerson();
                                    personruk.Surname = GetAttribute(xml, "Surname");
                                    personruk.Name = GetAttribute(xml, "Name");
                                    personruk.Patroname = GetAttribute(xml, "Patroname");
                                    personruk.ID_ParentRelation = 7;
                                    personruk.ID_Company = id_company;
                                    personruk.ID_AAddress = person.ID_AAddress;
                                    personruk.CreateTimeStamp = DateTime.Now;
                                    personruk.Level = 1;

                                    session.Save(personruk);


                                    CCPhone phRuk = new CCPhone();
                                    phRuk.ID_PhoneType = Convert.ToInt32(GetAttribute(xml, "TypePhone"));
                                    phRuk.ID_Customer = personruk.ID_Customer;
                                    phRuk.Number = Convert.ToInt64(GetAttribute(xml, "Phone"));
                                    phRuk.Mask = GetAttribute(xml, "Mask");
                                    session.Save(phRuk);

                                }
                                if (xml.Name == "KadrWork")
                                {
                                    CCPerson personruk = new CCPerson();
                                    personruk.Surname = GetAttribute(xml, "Surname");
                                    personruk.Name = GetAttribute(xml, "Name");
                                    personruk.Patroname = GetAttribute(xml, "Patroname");
                                    personruk.ID_ParentRelation = 10;
                                    personruk.ID_Company = id_company;
                                    personruk.ID_AAddress = person.ID_AAddress;
                                    personruk.CreateTimeStamp = DateTime.Now;
                                    personruk.Level = 1;

                                    session.Save(personruk);


                                    CCPhone ph = new CCPhone();
                                    ph.ID_PhoneType = Convert.ToInt32(GetAttribute(xml, "TypePhone"));
                                    ph.ID_Customer = personruk.ID_Customer;
                                    ph.Number = Convert.ToInt64(GetAttribute(xml, "Phone"));
                                    ph.Mask = GetAttribute(xml, "Mask");
                                    session.Save(ph);

                                }
                                if (xml.Name == "Other")
                                {
                                    cperson.CreateTimeStamp = DateTime.Now;
                                    cperson.WorkPlaceRegion = GetAttribute(xml, "WorkArea");
                                    cperson.WorkPlaceCity = GetAttribute(xml, "WorkCity");
                                    cperson.WorkPlaceStreet = GetAttribute(xml, "WorkStreet");
                                    cperson.WorkPlaceHouseNumber = GetAttribute(xml, "WorkHouseNumber");
                                    cperson.WorkPost = GetAttribute(xml, "WorkPost");
                                    cperson.WorkTime = Convert.ToDecimal(GetAttribute(xml, "WorkStag"));
                                    cperson.AvgIncome = Convert.ToDecimal(GetAttribute(xml, "AvgIncome")) * 1000;
                                    cperson.AvgOutgo = Convert.ToDecimal(GetAttribute(xml, "AvgOut")) * 1000;
                                    cperson.AdditionalIncome = Convert.ToDecimal(GetAttribute(xml, "DopIncome")) * 1000;
                                    cperson.PrepaymentDate = Convert.ToInt32(GetAttribute(xml, "PrepaymentDay"));
                                    cperson.SalaryDate = Convert.ToInt32(GetAttribute(xml, "SalaryDay"));
                                    cperson.NoAddress = "1".Equals(GetAttribute(xml, "WorkNoAddress"));
                                    cperson.Scope = GetAttribute(xml, "WorkSphere");
                                    cperson.WorkPlace = GetAttribute(xml, "WorkName");
                                    cperson.WorkLink = GetAttribute(xml, "WorkCiteAddress");
                                    cperson.HasDependents = "1".Equals(GetAttribute(xml, "HasDependens"));
                                    cperson.Dependents = Convert.ToInt32(GetAttribute(xml, "Dependents"));
                                    cperson.HasAvto = "1".Equals(GetAttribute(xml, "HasAvto"));
                                    cperson.AvtoMark = GetAttribute(xml, "AvtoMark");
                                    cperson.AvtoModel = GetAttribute(xml, "AvtoModel");
                                    cperson.AvtoNumber = GetAttribute(xml, "AvtoNumber");
                                    cperson.AvtoYear = GetAttribute(xml, "AvtoYear");
                                    cperson.AvtoProperty = "".Equals(GetAttribute(xml, "AvtoProperty")) ? 0 : Convert.ToDecimal(GetAttribute(xml, "AvtoProperty"));
                                    cperson.HasHome = "1".Equals(GetAttribute(xml, "HasHome"));
                                    cperson.HomeRegion = GetAttribute(xml, "HomeRegion");
                                    cperson.HomeCity = GetAttribute(xml, "HomeCity");
                                    cperson.HomeStreet = GetAttribute(xml, "HomeStreet");
                                    cperson.HomeHouseNumber = GetAttribute(xml, "HomeHouseNumber");
                                    cperson.HomeKorpus = GetAttribute(xml, "HomeHouseKorpus");
                                    cperson.HomeFlat = GetAttribute(xml, "HomeHouseFlat");
                                    cperson.HomeProperty = "".Equals(GetAttribute(xml, "HomeProperty")) ? 0 : Convert.ToDecimal(GetAttribute(xml, "HomeProperty"));
                                    cperson.HasCrime = "1".Equals(GetAttribute(xml, "Crime"));
                                    cperson.Crime = GetAttribute(xml, "crimeArticle");
                                    session.SaveOrUpdate(cperson);
                                }
                            }
                            #endregion

                            #region сохранение оплаты
                            if (xm.Name == "Pay")
                            {
                                List<CCPerson> lperson = (List<CCPerson>)session.CreateCriteria(typeof(CCPerson)).List<CCPerson>();
                                int id_customer = lperson.Find(delegate(CCPerson bk) { return (bk.PassportNum == Convert.ToInt64(GetAttribute(xm, "Passport")))&&(bk.ID_AAddress==id_affiliateaddress) ; }).ID_Customer;
                                
                                List<CCDocument> ldocument = (List<CCDocument>)session.CreateCriteria(typeof(CCDocument)).List<CCDocument>();
                                CCDeal deal = ldocument.Find(delegate(CCDocument bk) { return (bk.ID_Customer == id_customer && bk.ID_DocumentType == 3 && bk.Number == Convert.ToInt32(GetAttribute(xm, "Number"))); }).Deal;

                                DateTime dtValue = DateTime.MinValue;
                                DateTime.TryParse(GetAttribute(xm, "PaymentDate"), out dtValue);

                                decimal dValue = 0;
                                decimal.TryParse(GetAttribute(xm, "Amount"), out dValue);

                                PaymentRow row = null;
                                foreach (PaymentRow r in deal.paymentrow)
                                    if (r.RowDate == dtValue)
                                        row = r;

                                CCPayment Record = new CCPayment();
                                Record.ID_Deal = deal.ID_Deal;

                                //SaasUser user = SaasUser.GetUserById(SaasUser.IdFromCookie());
                                //Record.ID_User = user.ID_User;

                                int iAffiliateAddress = id_affiliateaddress;
                                //int.TryParse(hfAffiliateAddress.Value, out iAffiliateAddress);

                                if (iAffiliateAddress > 0)
                                    Record.ID_AffiliateAddress = iAffiliateAddress;
                                //else
                                //    Record.ID_AffiliateAddress = user.ID_AffiliateAddress;

                                Record.PlanDate = dtValue;
                                Record.FactBody = 0;

                                Record.FactAmount = dValue;
                                //Record.FactPercent = dPercent;

                                Record.PaymentPercent = 0;
                                Record.PaymentBody = 0;
                                decimal dt = (row.CreditPercentEnd - Record.PaymentPercent);
                                if (dt <= 0)
                                    dt = 0;
                                if (dValue >= dt)
                                {
                                    if (row.CreditPercentEnd < 0)
                                    {
                                        Record.PaymentBody += dValue;
                                    }
                                    else
                                    {
                                        Record.PaymentPercent += dt;
                                        Record.PaymentBody += dValue - dt;
                                    }
                                }
                                else
                                {
                                    Record.PaymentPercent += dValue;
                                }

                                session.SaveOrUpdate(Record);
                            }
                            #endregion
                        }
                    //}
                }
                
                
                tr.Commit();
                return true;
            }
            catch (Exception e)
            {               
                return false;
            }
        }
    }
}
